import json
import os

from oneconvert.datasource.base import BaseDataSource


class JsonDataSource(BaseDataSource):
    def read(self, encoding='utf-8', **kwargs):
        if not os.path.isfile(self.uri):
            raise ValueError(f'the file {self.uri} not found')

        with open(self.uri, 'r', encoding=encoding) as fp:
            return json.load(fp)

    def write(self, data, encoding='utf-8', indent: int = None, ensure_ascii: bool = False, sort_keys: bool = False,
              **kwargs):
        dir_name = os.path.dirname(self.uri)
        if dir_name and not os.path.exists(dir_name):
            os.makedirs(dir_name, exist_ok=True)

        with open(self.uri, 'w', encoding=encoding) as fp:
            json.dump(data, fp,
                      indent=indent,
                      ensure_ascii=ensure_ascii,
                      sort_keys=sort_keys)
